package com.laogu1.service;

import com.lagou.pojo.Request;
import com.lagou.service.IUserServer;
import com.lagou.service.impl.JSONSerializer;
import com.lagou.util.RpcDecoder;
import com.lagou.util.ZkUtil;
import com.laogu1.handler.UserServiceHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements IUserServer {

    // 客户端要远程调用的方法
    public String sayHello(String msg) {
        System.out.println(msg);
        return msg;
    }

    // 创建一个方法启动服务器
    public static void startServer(String ipAddress, int port) throws InterruptedException {
        // 1. 创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        // 2. 创建服务器端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        // 3. 配置启动引导对象
        serverBootstrap.group(bossGroup, workerGroup)
                // 设置通道为NIO
                .channel(NioServerSocketChannel.class)
                // 创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        // 获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();

                        // 给管道对象pipeline 设置编码
                        pipeline.addLast(new StringEncoder());
//                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new RpcDecoder(Request.class, new JSONSerializer()));
                        // 自定义一个ChannelHandler添加到通道中
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        // 4. 绑定端口
        serverBootstrap.bind(ipAddress, port).sync();
        System.out.println("服务器启动");

        registryZk(ipAddress, port);
    }

    /**
     * 向zk注册节点
     *
     * @param ipAddress
     * @param port
     */
    public static void registryZk(String ipAddress, int port) {
        ZkClient zkClient = new ZkClient(ZkUtil.ZK_ADDRESS);
        boolean exists = zkClient.exists(ZkUtil.PATH + "/" + ipAddress + "_" + port);
        long startTime = System.currentTimeMillis();

        if (!exists) {
            zkClient.createPersistent(ZkUtil.PATH + "/" + ipAddress + "_" + port, startTime + "_0");
        } else {
            zkClient.writeData(ZkUtil.PATH + "/" + ipAddress + "_" + port, startTime + "_0");
        }
    }
}
